package com.example.utils;

import com.example.spiders.constant.ConfigConstant;
import java.io.IOException;
import lombok.extern.log4j.Log4j2;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Description: HttpClient
 * @Auther: Swain
 * @Date: 2021/1/18 15:43
 * @Version 1.0.0
 */
@Log4j2
public class HttpClientUtils {

    /**
     * HttpClient 连接池管理类
     */
    private static PoolingHttpClientConnectionManager poolingHttpClientConnectionManager;

    /**
     * 请求配置
     */
    private static RequestConfig requestConfig;


    /**
     * 重试次数
     */
    private static int max_try_count = 0;


    /**
     * 当前已发送次数
     */
    private static ThreadLocal<Integer> current_try_count = new ThreadLocal<>();

    static {
        requestConfig = RequestConfig.custom()
            .setConnectionRequestTimeout(ConfigConstant.TIME_OUT)
            .setConnectTimeout(ConfigConstant.TIME_OUT)
            .setSocketTimeout(ConfigConstant.TIME_OUT).build();

        poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
        /**
         * 整个连接池的最大连接数
         */
        poolingHttpClientConnectionManager.setMaxTotal(50);
        /**
         * 到单个主机的最大连接数
         */
        poolingHttpClientConnectionManager.setDefaultMaxPerRoute(10);

        max_try_count = ConfigConstant.TRY_MAX_COUNT;

    }

    public static CloseableHttpClient getHttpClient() {
        return HttpClients.custom()
            .setConnectionManager(poolingHttpClientConnectionManager)
            .setDefaultRequestConfig(requestConfig)
            .build();
    }


    public static String getHtml(String url) {
        if (null == current_try_count.get()) {
            current_try_count.set(0);
        }
        if (current_try_count.get() == max_try_count) {
            return null;
        }
        HttpGet get = new HttpGet(url);
        get.setHeader("User-Agent", HeaderUtils.getRandomHeader());
        get.setHeader("referer", url);
        String html = null;
        try (CloseableHttpResponse response = getHttpClient().execute(get)) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                throw new Exception("请求失败[" + url + "]");
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                html = EntityUtils.toString(entity, "UTf-8");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            current_try_count.set(current_try_count.get() + 1);
            log.info("["+url+"]"+"准备重试:第" + current_try_count.get()+"次");
            getHtml(url);
        }
        return html;
    }


}
